<template>
  <div class="coupon-add">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>新增优惠券</span>
        </div>
      </template>

      <el-form 
        :model="couponForm" 
        :rules="rules" 
        ref="formRef" 
        label-width="120px"
        style="max-width: 600px"
      >
        <el-form-item label="优惠券名称" prop="name">
          <el-input v-model="couponForm.name" placeholder="请输入优惠券名称"></el-input>
        </el-form-item>

        <el-form-item label="使用范围" prop="specific">
          <el-radio-group v-model="couponForm.specific">
            <el-radio :label="false">全部课程分类</el-radio>
            <el-radio :label="true">指定课程分类</el-radio>
          </el-radio-group>
          <el-select v-model="couponForm.scopes" placeholder="请选择课程分类" multiple v-if="couponForm.specific">
            <!-- 这里需要动态加载课程分类 -->
          </el-select>
        </el-form-item>

        <el-form-item label="优惠券类型" prop="discountType">
          <el-radio-group v-model="couponForm.discountType">
            <el-radio :label="1">每满减</el-radio>
            <el-radio :label="2">折扣</el-radio>
            <el-radio :label="3">无门槛</el-radio>
            <el-radio :label="4">满减</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="门槛金额" prop="thresholdAmount" v-if="couponForm.discountType !== 3">
          <el-input-number v-model="couponForm.thresholdAmount" :min="0"></el-input-number>
        </el-form-item>

        <el-form-item label="优惠金额/折扣" prop="discountValue">
          <el-input-number v-model="couponForm.discountValue" :min="0"></el-input-number>
        </el-form-item>

        <el-form-item label="最大优惠金额" prop="maxDiscountAmount" v-if="couponForm.discountType === 1 || couponForm.discountType === 4">
          <el-input-number v-model="couponForm.maxDiscountAmount" :min="0"></el-input-number>
        </el-form-item>

        <el-form-item label="推广方式" prop="obtainWay">
          <el-radio-group v-model="couponForm.obtainWay">
            <el-radio :label="1">手动领取</el-radio>
            <el-radio :label="2">指定发放</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="发放数量" prop="totalNum">
          <el-input-number v-model="couponForm.totalNum" :min="0"></el-input-number>
        </el-form-item>

        <el-form-item label="每人限领" prop="userLimit">
          <el-input-number v-model="couponForm.userLimit" :min="0"></el-input-number>
        </el-form-item>

        <el-form-item label="领用/使用期限">
          <el-radio-group v-model="formExtra.immediate">
            <el-radio :label="true">立刻发放</el-radio>
            <el-radio :label="false">定时发放</el-radio>
          </el-radio-group>
          <el-date-picker
            v-model="formExtra.issueBeginTime"
            type="datetime"
            placeholder="选择日期时间"
            v-if="!formExtra.immediate"
          ></el-date-picker>
          <el-date-picker
            v-model="formExtra.issueEndTime"
            type="datetime"
            placeholder="选择日期时间"
            v-if="!formExtra.immediate"
          ></el-date-picker>
        </el-form-item>

        <el-form-item label="使用期限方式">
          <el-radio-group v-model="formExtra.fixedDays">
            <el-radio :label="true">固定天数</el-radio>
            <el-radio :label="false">固定时间段</el-radio>
          </el-radio-group>
          <el-input-number v-model="formExtra.termDays" :min="0" v-if="formExtra.fixedDays"></el-input-number>
          <el-date-picker
            v-model="formExtra.termBeginTime"
            type="datetime"
            placeholder="选择日期时间"
            v-if="!formExtra.fixedDays"
          ></el-date-picker>
          <el-date-picker
            v-model="formExtra.termEndTime"
            type="datetime"
            placeholder="选择日期时间"
            v-if="!formExtra.fixedDays"
          ></el-date-picker>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="submitLoading">
            添加优惠券
          </el-button>
          <el-button @click="resetForm">重置</el-button>
          <el-button @click="goBack">返回</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import couponApi, { type CouponFormDTO } from '@/api/coupon'

// 表单引用
const formRef = ref()

// 路由和参数
const route = useRoute()
const router = useRouter()

// 表单数据
const couponForm = ref<CouponFormDTO>({
  id: '',
  name: '',
  discountType: 1,
  thresholdAmount: 0,
  discountValue: 0,
  maxDiscountAmount: 0,
  obtainWay: 1,
  totalNum: 0,
  userLimit: 0,
  specific: false,
  scopes: []
})

// 额外的表单控制数据
const formExtra = ref({
  immediate: true, // 是否立刻发放
  issueBeginTime: '', // 发放开始时间
  issueEndTime: '', // 发放结束时间
  fixedDays: true, // 使用期限方式：固定天数
  termDays: 0, // 固定天数
  termBeginTime: '', // 固定时间段开始时间
  termEndTime: '' // 固定时间段结束时间
})

// 提交按钮加载状态
const submitLoading = ref(false)

// 验证发放时间
const validateIssueTime = (rule: any, value: string, callback: any) => {
  if (formExtra.value.immediate) {
    callback()
  } else {
    if (!value) {
      return callback(new Error('请选择时间'))
    }
    callback()
  }
}

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入优惠券名称', trigger: 'blur' }
  ],
  discountType: [
    { required: true, message: '请选择优惠券类型', trigger: 'change' }
  ],
  thresholdAmount: [
    { required: true, message: '请输入门槛金额', trigger: 'blur' }
  ],
  discountValue: [
    { required: true, message: '请输入优惠金额/折扣', trigger: 'blur' }
  ],
  totalNum: [
    { required: true, message: '请输入发放数量', trigger: 'blur' }
  ],
  userLimit: [
    { required: true, message: '请输入每人限领数量', trigger: 'blur' }
  ],
  issueBeginTime: [
    { required: true, message: '请选择发放开始时间', trigger: 'change' },
    { validator: validateIssueTime, trigger: 'change' }
  ],
  issueEndTime: [
    { required: true, message: '请选择发放结束时间', trigger: 'change' },
    { validator: validateIssueTime, trigger: 'change' }
  ],
  termDays: [
    { required: true, message: '请输入使用期限天数', trigger: 'blur' }
  ],
  termBeginTime: [
    { required: true, message: '请选择使用期限开始时间', trigger: 'change' }
  ],
  termEndTime: [
    { required: true, message: '请选择使用期限结束时间', trigger: 'change' }
  ]
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      submitLoading.value = true
      try {
        // 新增优惠券
        const res: any = await couponApi.addCoupon(couponForm.value)
        
        if (res.data.code === 200) {
          ElMessage.success('添加优惠券成功')
          router.push('/coupon/list')
        } else {
          ElMessage.error(`添加优惠券失败: ${res.data.msg}`)
        }
      } catch (error) {
        ElMessage.error('添加优惠券失败')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 重置表单
const resetForm = () => {
  couponForm.value = {
    id: '',
    name: '',
    discountType: 1,
    thresholdAmount: 0,
    discountValue: 0,
    maxDiscountAmount: 0,
    obtainWay: 1,
    totalNum: 0,
    userLimit: 0,
    specific: false,
    scopes: []
  }
  formExtra.value = {
    immediate: true,
    issueBeginTime: '',
    issueEndTime: '',
    fixedDays: true,
    termDays: 0,
    termBeginTime: '',
    termEndTime: ''
  }
}

// 返回上一页
const goBack = () => {
  router.go(-1)
}

// 初始化
onMounted(() => {
  // 初始化逻辑（如果需要）
})
</script>

<style scoped>
.coupon-add {
  padding: 20px;
}

.card-header {
  font-size: 18px;
  font-weight: bold;
}
</style>